module uart_recive
(
	input            clk          ,
	input            rstn         ,
	
	input            uart_rxd     ,
	output reg       uart_done    ,
	output reg [7:0] uart_data
);
/*
parameter CLK_RED = 50_000_000;
parameter UART_BPS = 9600;

localparam BPS_CNT = CLK_RED / (UART_BPS * 16);
*/

reg        uart_rxd_d0;
reg        uart_rxd_d1;
reg [15:0] clk_cnt;
reg [3:0]  rx_cnt;
reg [7:0]  rx_data;
reg        rx_flag;

wire start_flag;

always@(posedge clk or negedge rstn) begin
      if(!rstn)
		       begin 
		       uart_rxd_d0 <= 1'b0;
             uart_rxd_d1 <= 1'b0;
             end 
	   else begin 
		       uart_rxd_d0 <= uart_rxd;
		       uart_rxd_d1 <= uart_rxd_d0;
			    end 
end 

assign start_flag = uart_rxd_d1 & (~uart_rxd_d0);

always@(posedge clk or negedge rstn)begin
      if(!rstn)
		       rx_flag <= 1'b0;
		else begin
		    if(start_flag)
			    rx_flag <= 1'b1;
			 if((rx_cnt == 4'd9 )&& (clk_cnt == 163))
			    rx_flag <= 1'b0;
				 
			 else 
			    rx_flag <= rx_flag;
			  end 
end 

always@(posedge clk or negedge rstn)begin
      if(!rstn)
		       rx_cnt <= 1'b0;
		else if(rx_flag)
		    if(clk_cnt <325 )
			 begin
				 clk_cnt <= clk_cnt + 1'b1;
				 rx_cnt  <= rx_cnt;
			 end 
			 else begin
				 clk_cnt <= 1'b0;
				 rx_cnt  <= rx_cnt + 1'b1;
			 end 
end 

always@(posedge clk or negedge rstn)begin
      if(!rstn)
		  rx_data <= 1'b0;
		else if(rx_flag) 
		    if(clk_cnt == 163) begin
			  case(rx_cnt)
			  4'd1: rx_data[0] <= uart_rxd_d1;
			  4'd2: rx_data[1] <= uart_rxd_d1;
			  4'd3: rx_data[2] <= uart_rxd_d1;
			  4'd4: rx_data[3] <= uart_rxd_d1;
			  4'd5: rx_data[4] <= uart_rxd_d1;
		     4'd6: rx_data[5] <= uart_rxd_d1;
		     4'd7: rx_data[6] <= uart_rxd_d1;
		     4'd8: rx_data[7] <= uart_rxd_d1;
			  
			  default :;
			  endcase
		end 
			  else 
			    rx_data <= rx_data;
			
	   else 
		  rx_data <= 8'd0;
end 

always @(posedge clk or negedge rstn)begin 
        if(!rstn) begin 
		      uart_done <= 1'b0;
			   uart_data <= 8'd0;
			  end 
		  else if(rx_cnt == 4'd9) begin 
		      uart_data <= rx_data ;
				uart_done <= 1'b1;
				end 
		  else begin
		      uart_done <= 1'b0;
			   uart_data <= 8'd0;
		  end 
end 
			  
endmodule 
				    
				    

					 

















